<?php
  include('header.php');
  $pageTitle = $l_forumname;
  echo '<h3>Sign in</h3><hr /><br />';
  //first, check if the user is already signed in. If that is the case, there is no need to display this page
  if (isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
    {
      echo 'You are already signed in, you can <a class="loginlink" href="signout.php">sign out</a> if you want.';
    }
  else
    {
      if ($_SERVER['REQUEST_METHOD'] != 'POST')
        {
          /*the form hasn't been posted yet, display it
           note that the action="" will cause the form to post to the same page it is on */
          $tags = array('{LOGIN}', '{USERNAME}', '{PASSWORD}', '{REGISTER}', '{FORGOT}', '{REMEMBER}','{MAX_UN}');
          $data = array($l_login, $l_un2, $l_password2, $l_register, $l_change_pw_title, $l_rememberme,$max_username_char);
          
          echo str_replace($tags, $data, file_get_contents("./style/" . $default_style . "/login.html"));
        }
      else
        {
          /* so, the form has been posted, we'll process the data in three steps:
           1.  Check the data
           2.  Let the user refill the wrong fields (if necessary)
           3.  Varify if the data is correct and return the correct response
           */
          $errors = array();
          /* declare the array for later use */
          if (!isset($_POST['user_name']))
            {
              $errors[] = $l_error_un_empty;
            }
          if (!isset($_POST['user_pass']))
            {
              $errors[] = $l_error_pw_empty;
            }
          if (!empty($errors))
            {
              /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
              echo $l_error_message . '<br /><br />';
              echo '<ul>';
              foreach ($errors as $key => $value)
                {
                  /* walk through the array so all the errors get displayed */
                  echo '<li>' . $value . '</li>';
                  /* this generates a nice error list */
                }
              echo '</ul>';
            }
          else
            {
              //the form has been posted without errors, so save it
              //notice the use of mysql_real_escape_string, keep everything safe!
              //also notice the sha1 function which hashes the password    
              $result = $db->query("SELECT  user_id, user_name, user_level, user_lang, activation_code FROM " . $table_prefix . "users
WHERE user_name = '" . mysql_real_escape_string($_POST['user_name']) . "' AND user_pass = '" . sha1(mysql_real_escape_string($_POST['user_pass'])) . "' LIMIT 1");
              if (!$result)
                {
                  //something went wrong, display the error
                  echo 'Something went wrong while signing in. Please try again later.';
                  //echo mysql_error(); //debugging purposes, uncomment when needed
                }
              else
                {
                  //the query was successfully executed, there are 2 possibilities
                  //1. the query returned data, the user can be signed in
                  //2. the query returned an empty result set, the credentials were wrong
                  if (mysql_num_rows($result) == 0)
                    {
                      echo '<div align="center"><span style="color:red">' . $l_error_wrong_unpw . '</span><br /><a class="loginlink" href="signin.php"><br />' . $l_back_to_prev . '</a>.</div><br>';
                      if ($flood_login_attempt >= 1)
                        {
                          if ($_SESSION['flood'] <= $flood_login_attempt)
                            {
                              $_SESSION['flood'] += 1;
                              echo "<br><br><div align='center'><span style='color:red'> Attempts: " . $_SESSION['flood'] . " of " . $flood_login_attempt . "</span></div><br>";
                            }
                          if ($_SESSION['flood'] >= $flood_login_attempt)
                            {
                              $result2 = $db->query("INSERT INTO " . $table_prefix . "banlist(ban_ip,ban_reason,ban_time) VALUES('" . $_SERVER["REMOTE_ADDR"] . "','Flood',NOW() + INTERVAL $flood_ban MINUTE + INTERVAL " . $server_time . " MINUTE + INTERVAL " . $time_difference . " HOUR)") or die(mysql_error());
                              session_destroy();
                              session_start();
                              $_SESSION['flood'] = 0;
                            }
                        }
                    }
                  else
                    {
					 $remember = "";
                      //SET cookie
                      if (isset($_POST['rememberme']))
                        {
                          /* Set cookie to last 1 year */
                          setcookie('bb_auth', session_id(), time() + 60 * 60 * 24 * 365);
						  $remember = ", session = '".session_id()."' ";
                        }
                      else
                        {
                          /* Cookie expires when browser closes */
                          setcookie('bb_auth', '', false);
                        }
                      //END cookie
                      //we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
                      while ($row = $db->fetch_array($result,'assoc'))
                        {
                          $expired = 0;
                          $check_ban = $db->query("SELECT * FROM " . $table_prefix . "banlist WHERE ban_userid = $row[user_id] LIMIT 1");
                          $bans = $db->fetch_array($check_ban,'assoc');
                          if ($bans['ban_userid'] == $row['user_id'])
                            {
                              if ($bans['ban_time'] == "0000-00-00 00:00:00")
                                {
                                  $ban_str = "";
                                }
                              else
                                {
                                  $ban_time = date($date_format, strtotime($bans['ban_time']));
                                  $ban_str = "(Expires: " . $ban_time . ")";
                                  $time = strtotime($time_difference . " hours");
                                }
                              $time = strtotime($time_difference . " hours");
                              if (date($date_format, $time) >= $ban_time and $bans['ban_time'] != "0000-00-00 00:00:00")
                                {
                                  $result2 = $db->query("DELETE FROM " . $table_prefix . "banlist WHERE ban_userid = $row[user_id]");
								  $result21 = mysql_query("UPDATE ".$table_prefix."users SET is_banned = 0 WHERE user_id = $row[user_id]");
                                  $expired = 1;
                                }
                              else
                                {
                                  $pageTitle = "$l_you_banned";
                                  $pageContents = ob_get_contents();
                                  ob_end_clean();
                                  echo str_replace('<!--TITLE-->', $pageTitle, $pageContents);
                                  echo "<div align='center'><br /><b>$l_you_banned</b><br /><br />" . $ban_str . "</div>";
                                  if ($bans['ban_reason'] != "")
                                    {
                                      echo "<br /><div align='center'><b>$l_ban_reason</b> " . $bans['ban_reason'] . "</div><br /><br />";
                                    }
                                  $_SESSION['signed_in'] = null;
                                  die;
                                }
                            }
                          if ($expired == 0)
                            {
                              $check_banip = $db->query("SELECT * FROM " . $table_prefix . "banlist WHERE ban_ip = '" . $_SERVER["REMOTE_ADDR"] . "'") or die(mysql_error());
                              $bans2 = $db->fetch_array($check_banip,'assoc');
                              if ($bans2['ban_ip'] == $_SERVER["REMOTE_ADDR"])
                                {
                                  $pageTitle = "$l_ban_ip";
                                  $pageContents = ob_get_contents();
                                  ob_end_clean();
                                  echo str_replace('<!--TITLE-->', $pageTitle, $pageContents);
                                  
                                  echo "<div align='center'><br /><b>$l_ban_ip</b></div><br />";
                                  $_SESSION['signed_in'] = null;
                                  die;
                                }
                            }
                          if ($email_activation == 1 and $_SESSION['signed_in'] == false)
                            {
                              if ($row['activation_code'] != "")
                                {
                                  echo "<div align='center'><br /><b>Before you proceed you must activate your account.</b></div><br />";
                                  $_SESSION['signed_in'] = null;
                                  $_SESSION['user_id'] = null;
                                  $_SESSION['user_name'] = null;
                                  $_SESSION['user_level'] = null;
                                  die;
                                }
                            }
							 if (empty($errors)){
						  $_SESSION['signed_in'] = true;
                          $_SESSION['user_id'] = mysql_real_escape_string($row['user_id']);
                          $_SESSION['user_name'] = mysql_real_escape_string($row['user_name']);
                          $_SESSION['user_level'] = mysql_real_escape_string($row['user_level']);
                          $_SESSION['user_ip'] = mysql_real_escape_string($_SERVER["REMOTE_ADDR"]);
                          $_SESSION['user_lang'] = mysql_real_escape_string($row['user_lang']);
                          $_SESSION['flood'] = 0;
                          }
						  else
						  {
                                  $_SESSION['signed_in'] = null;
                                  $_SESSION['user_id'] = null;
                                  $_SESSION['user_name'] = null;
                                  $_SESSION['user_level'] = null;						  
						  }
						  $user_agent = $_SERVER['HTTP_USER_AGENT'];
						  
                          $result2 = $db->query("UPDATE " . $table_prefix . "users SET user_last_login = NOW() + INTERVAL $server_time MINUTE + INTERVAL $time_difference HOUR $remember, user_browser = '$user_agent' WHERE user_id = $_SESSION[user_id]");
                          
                          //Delete user activity on login
                          $delete_activities = $db->query("DELETE FROM " . $table_prefix . "topics_track WHERE user_id = $_SESSION[user_id] ");
                        }
                      
                      $return_to = "index.php";
                      $last_visited = "";
                      $userIP = $_SERVER["REMOTE_ADDR"];
                      if ($log_userip == 1)
                        {
                          $result = $db->query("UPDATE " . $table_prefix . "users SET user_ip='$userIP' WHERE user_id = $_SESSION[user_id]");
                        }
                      if (!isset($_GET['f']) and !isset($_GET['t']))
                        {
                          $return_to = "index.php";
                          $last_visited = '';
                        }
                      if (isset($_GET['f']))
                        {
                          $return_to = "category.php";
                          $last_visited = '<br />' . $l_return_to . '<br />';
                        }
                      if (isset($_GET['t']) and $_GET['t']!="")
                        {
                          $return_to = "topic.php";
                          $last_visited = '<br />' . $l_return_to_topic . '<br />';
                        }
                      
                      echo '<div align="center">' . $l_welcome . ' <b>' . $_SESSION['user_name'] . ' </b><br /><a class="loginlink" href="' . $return_to . '?f=' . $fid . '&t='.$topicid.'&page=' . $page . '">' . $last_visited . '</a><a class="loginlink" href="index.php"><br />' . $l_back_to . '</a>.</div><br /><br />';
                      echo '<meta http-equiv="refresh" content="3;url=' . $return_to . '?f=' .$fid . '&t=' . $topicid . '&page=' . $page . '" />';
                    }
                }
            }
        }
    }
  $pageContents = ob_get_contents();
  ob_end_clean();
  echo str_replace('<!--TITLE-->', $pageTitle, $pageContents);
?>